<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/3/3
 * Time: 20:52
 */

namespace app\admin\controller;

use app\admin\common\Base;

/**
 * Class Role 角色控制器
 * @package app\admin\controller
 */
class Role extends Base{
    public function index($page=1,$limit=10,$keyword=''){
        if (request()->isPost()){
            $where = [];
            if (!empty($keyword)){
                $where[] = ['name','like','%'.$keyword.'%'];
            }
            $count = db('role')->where($where)->count();
            $list = db('role')
                ->where($where)
                ->page($page,$limit)
                ->select();
            return json(['code'=>'suc','msg'=>'请求数据成功','count'=>$count,'data'=>$list]);
        }

        return $this->fetch();
    }

    public function add()
    {
        if (request()->isPost()) {
            $name = input('post.name');
            $status = 1;

            if (empty($name)) {
                return json(['code' => 'err', 'msg' => '名称不能为空']);
            }
            $data['name'] = $name;
            if (empty(input('post.status'))) {
                $status = 0;
            }
            $data['status'] = $status;
            $data['create_time'] = time();
            $data['update_time'] = time();

            $repeat = db('role')->where('name', $name)->find();
            if ($repeat) {
                return json(['code' => 'err', 'msg' => '角色“' . $name . '”已存在']);
            }

            $result = db('role')->data($data)->insert();
            if ($result) {
                insert_system_log('添加角色：' . $name);
                return json(['code' => 'suc', 'msg' => '添加成功']);
            } else {
                return json(['code' => 'err', 'msg' => '添加失败']);
            }
        }

        return $this->fetch();
    }

    /**
     * 编辑角色
     * @param string|int $id 角色id
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id){
        if (request()->isPost()){
            $name = input('post.name');//角色名称
            $status = input('post.status');//角色状态
            $checked_list = input('post.checked_list');//选中的权限id
            $check_node = json_decode($checked_list,true);
            if (empty($name)){
                return json(['code' => 'err', 'msg' => '名称不能为空']);
            }
            $status = empty($status) ? 0 : 1;

            $role_rule = [];
            foreach ($check_node as $k => $v){
                $role_rule[$k]['role_id'] = intval($id);
                $role_rule[$k]['rule_id'] = $v;
            }

            $role_update = [
                'name' => $name,
                'status' => $status,
                'update_time' => time()
            ];

            $repeat = db('role')
                ->where('id','<>',$id)
                ->where('name',$name)
                ->find();
            if (!$repeat){
                //启动事务
                db()->startTrans();
                try{
                    db('role_rule')->where('role_id',$id)->delete();
                    db('role_rule')->insertAll($role_rule);
                    db('role')->where('id',$id)->update($role_update);
                    insert_system_log('编辑角色：'.$name);
                    db()->commit();
                    $json = ['code' => 'suc', 'msg' => '编辑成功'];
                }catch (\Exception $e){
                    db()->rollback();
                    $json = ['code' => 'err', 'msg' => '编辑失败'];
                }
            }else{
                $json = ['code' => 'err', 'msg' => '角色“' . $name . '”已存在'];
            }
            return json($json);
        }

        $info = db('role')->where('id',$id)->find();
        $this->assign('info',$info);
        return $this->fetch();
    }

    public function del($id){
        if (is_post()){
            //开启事务
            db()->startTrans();
            try{
                db('role')->where('id',$id)->delete();
                db('role_rule')->where('role_id',$id)->delete();
                insert_system_log('删除角色：' . $id);
                //提交事务
                db()->commit();
                return json(['code' => 'suc', 'msg' => '删除成功']);
            }catch (\Exception $e){
                //事务回滚
                db()->rollback();
                return json(['code' => 'err', 'msg' => '删除失败']);
            }
        }
    }

    public function changeStatus($type,$id){
        if (is_post()){
            if ($this->changeRecordStatus('role',$id,1,$type)){
                if ($type == 1){
                    $log_msg = '启用角色：' . $id;
                    $msg = '已启用';
                }else{
                    $log_msg = '停用角色：' . $id;
                    $msg = '已停用';
                }
                insert_system_log($log_msg);
                return json(['code' => 'suc','msg' => $msg]);
            }
            return json(['code' => 'err','msg' => '系统繁忙，请重试']);
        }
    }

    /**
     * 当前角色可访问的菜单
     * @param $id 角色id
     * @return \think\response\Json
     */
    public function nodeList($id){
        $node_list = db('role_rule')
            ->where('role_id',$id)
            ->column('rule_id');
        $node_list = array_unique($node_list);
        return json(['code' => 'suc','msg' => '请求数据成功','data' => $node_list]);
    }
}